package com.atguigu.gmall.realtime.utils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Author: Felix
 * Date: 2021/12/3
 * Desc: 日期工具类
 *  SimpleDateFormat存在线程安全问题
 *  使用JDK1.8之后提供的日期相关类进行替代
 *  SimpleDateFormat --->DateTimeFormatter
 *  Date             --->LocalDateTime
 *  Calendar         --->Instant
 */
public class DateTimeUtil {
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //将日期对象转换为字符串日期
    public static String toYmdhms(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        String dateStr = dtf.format(localDateTime);
        return dateStr;
    }

    //将字符串类型日期转换为时间毫秒数
    public static Long toTs(String dateStr){
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtf);
        Instant instant = localDateTime.toInstant(ZoneOffset.of("+8"));
        Long ts = instant.toEpochMilli();
        return ts;
    }

    public static void main(String[] args) {
        System.out.println(ZoneId.systemDefault());
    }
}
